package com.hy.admin.service.impl;

import com.hy.admin.dao.ImageDao;
import com.hy.admin.dao.MemberDao;
import com.hy.admin.entity.ImageEntity;
import com.hy.admin.entity.MemberEntity;
import com.hy.admin.enums.EnumImageRelatedType;
import com.hy.admin.enums.EnumIsDelete;
import com.hy.admin.enums.EnumStatus;
import com.hy.admin.helper.request.AccountRequest;
import com.hy.admin.helper.request.MemberRequest;
import com.hy.admin.service.MemberService;
import com.hy.core.response.ServicesResult;
import com.hy.utils.CommonUtility;
import com.hy.utils.OSSUtil;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by shitou on 17/12/28.
 */
@Service
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private ImageDao imageDao;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServicesResult<Boolean> Update(MemberRequest memberRequest, MultipartFile file) throws Exception {
        ServicesResult<Boolean> servicesResult = new ServicesResult<>();
        if (memberRequest == null || memberRequest.getId() == 0) {
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        MemberEntity memberEntity = memberDao.selectById(memberRequest.getId());
        if(memberEntity == null){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("用户不存在");
            return servicesResult;
        }
        String filePath = null;
        if(file != null) {
            //查询用户头像
            List<String> imageList = imageDao.selectByRelatedIdAndType(memberRequest.getId(), EnumImageRelatedType.HEAD_IMAGE.getId());
            if(imageList != null && !imageList.isEmpty()){
                if(file != null) {
                    imageDao.updateDeleteState(memberRequest.getId(), EnumImageRelatedType.HEAD_IMAGE.getId());
                    //删除原有图片
                    OSSUtil.deleteFile(imageList.get(0));
                }
            }

            //上传新图片
            String fileName = file.getOriginalFilename();
            String fileType = fileName.substring(fileName.indexOf(".") + 1, fileName.length());
            filePath = OSSUtil.uploadFile(CommonUtility.multipartToFile(file), fileType);
            if (filePath == null || StringUtils.isEmpty(filePath)) {
                //图片上传失败
                servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
                servicesResult.setStatusMsg("文件上传oss失败");
                return servicesResult;
            }
            //保存图片数据
            ImageEntity image = new ImageEntity();
            image.setImgPath(filePath);
            image.setRelatedId(memberRequest.getId());
            image.setRelatedType(EnumImageRelatedType.HEAD_IMAGE.getId());
            Calendar cal = Calendar.getInstance();
            image.setCreateTime(cal.getTime());
            image.setUpdateTime(cal.getTime());
            image.setStatus(EnumStatus.VALID.getId());
            image.setIsDelete(EnumIsDelete.NO.getId());
            int count = imageDao.insertSelective(image);
            if (count <= 0) {
                //删除已上传的图片
                OSSUtil.deleteFile(filePath);
                servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
                servicesResult.setStatusMsg("数据插入失败");
                return servicesResult;
            }
        }
        memberEntity.updateData(memberRequest);
        memberEntity.setUpdateTime(new Date());
        int count = memberDao.update(memberEntity);
        if(count <= 0 && !StringUtils.isEmpty(filePath)){
            //删除已上传的图片
            OSSUtil.deleteFile(filePath);
            //抛出异常回滚数据
            throw new Exception("修改数据失败");
        }
        servicesResult.setResult(true);
        return servicesResult;
    }

    @Override
    public ServicesResult<Boolean> IsExist(AccountRequest accountRequest) {
        ServicesResult<Boolean> servicesResult = new ServicesResult<>();
        List<MemberEntity> memberEntityList = memberDao.selectByMobile(accountRequest.getMobile());
        if (!memberEntityList.isEmpty()) {
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("手机号已注册");
            return servicesResult;
        }
        servicesResult.setResult(true);
        return servicesResult;
    }

    @Override
    public ServicesResult<Boolean> upload(Long memberId, MultipartFile file) throws IOException {
        ServicesResult<Boolean> servicesResult = new ServicesResult<>();
        if (memberId == null || memberId <= 0) {
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        MemberEntity memberEntity = memberDao.selectById(memberId);
        //上传新图片
        String fileName = file.getOriginalFilename();
        String fileType = fileName.substring(fileName.indexOf(".") + 1, fileName.length());
        String filePath = OSSUtil.uploadFile(CommonUtility.multipartToFile(file), fileType);
        if (filePath == null || StringUtils.isEmpty(filePath)) {
            //图片上传失败
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("文件上传oss失败");
            return servicesResult;
        }

        memberEntity.setCertPic(filePath);
        memberEntity.setUpdateTime(new Date());
        int count = memberDao.updateCertPic(memberEntity);
        if(count <= 0){
            //图片上传失败
            OSSUtil.deleteFile(filePath);
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("数据保存失败");
            return servicesResult;
        }
        servicesResult.setResult(true);
        return servicesResult;
    }

    @Override
    public ServicesResult<Boolean> updDeviceToken(Long memberId, String deviceToken) {
        ServicesResult<Boolean> servicesResult = new ServicesResult<>();
        if (memberId == null || memberId <= 0) {
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        if(StringUtils.isBlank(deviceToken)){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        //更新deviceToken、
        int count = memberDao.updateDeviceToken(memberId,deviceToken);
        if(count <= 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("修改失败");
            return servicesResult;
        }
        servicesResult.setResult(true);
        return servicesResult;
    }

    @Override
    public ServicesResult<Boolean> updAliDeviceId(Long memberId, String aliDeviceId) {
        ServicesResult<Boolean> servicesResult = new ServicesResult<>();
        if (memberId == null || memberId <= 0) {
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        if(StringUtils.isBlank(aliDeviceId)){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        //更新deviceId
        int count = memberDao.updateAliDeviceId(memberId,aliDeviceId);
        if(count <= 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("修改失败");
            return servicesResult;
        }
        servicesResult.setResult(true);
        return servicesResult;
    }
}
